package chances.declare.web;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import chances.commons.crypto.CodeUtils;
import chances.declare.entity.CPContent;
import chances.declare.entity.UnitContent;
import chances.declare.repo.CPContentRepository;
import chances.declare.repo.UnitContentRepository;
import chances.declare.service.CPContentService;
import chances.declare.service.UnitContentService;
import chances.declare.service.WriteDeclareExcelService;
import chances.declare.util.JsonBody;
import chances.declare.util.PageUtil;
import chances.system.json.JsonResponse;
import chances.system.log.entity.ActionLog;
import chances.system.log.entity.CompareLog;
import chances.system.operator.entity.EnumData;
import chances.system.operator.entity.Operator;
import chances.system.operator.entity.Oplog;
import chances.system.service.EnumService;

/**
*@Author Guoyh
*@Date 2017年7月26日 下午5:27:23
*chances.declare.web
*/
@RestController
public class UnitContentController {

    @Autowired
    private CPContentRepository cpContentRepository;

    @Autowired
    private UnitContentRepository unitContentRepository;

    @Autowired
    private UnitContentService unitContentService;

    @Autowired
    private CPContentService cpContentServer;

    @Autowired
    private EnumService enumService;

    private static final Logger logger = LoggerFactory.getLogger(UnitContentController.class);

    // 获取申报数据
    @RequestMapping(value = "/getUnitContentCPContent", method = RequestMethod.GET)
    public JsonBody getUnitContentCPContent(HttpServletRequest request,
            @RequestAttribute MergerModel model) {
        String page = request.getParameter("page");
        String size = request.getParameter("size");
        int pageNum = 0;
        int sizeNum = 20;
        if (!"".equals(page)) {
            pageNum = Integer.parseInt(page);
        }
        if (!"".equals(size)) {
            sizeNum = Integer.parseInt(size);
            if (sizeNum < 1)
                sizeNum = 1;
        }
        JsonBody jsonBody = new JsonBody();
        Pageable pageable = new PageRequest(pageNum, sizeNum);
        try {
            Page<UnitContentCPContent> pageData = unitContentService.getUnitContentCPContent(model,
                    pageable);
            jsonBody.setData(pageData);
            PageUtil pageUtil = new PageUtil();
            pageUtil.setNumber(pageData.getNumber());
            pageUtil.setSize(pageData.getSize());
            pageUtil.setTotalElements(pageData.getTotalElements());
            pageUtil.setTotalPages(pageData.getTotalPages());
            jsonBody.setPage(pageUtil);
            Map<String, Object> mapLink = new HashMap<String, Object>();
            // 首页
            Map<String, String> first = new HashMap<String, String>();
            first.put("href", request.getRequestURL() + "?sort=id,desc&size=" + pageData.getSize()
                    + "&page=0");
            mapLink.put("first", first);
            // 尾页
            Map<String, String> last = new HashMap<String, String>();
            last.put("href", request.getRequestURL() + "?sort=id,desc&size=" + pageData.getSize()
                    + "&page=" + (pageData.getTotalPages() - 1));
            mapLink.put("last", last);
            jsonBody.set_links(mapLink);

        } catch (Exception e) {
            logger.error(e.toString(), e);
            jsonBody.setErrorResult(e.getMessage());
            return jsonBody;
        }
        return jsonBody;
    }

    // 内容采纳,数据的查询
    @RequestMapping(value = "/adoptDeclareSearch", method = RequestMethod.GET)
    public JsonBody adoptDeclareSearch(HttpServletRequest request,
            @RequestAttribute MergerModel model) {
        String page = request.getParameter("page");
        String size = request.getParameter("size");
        int pageNum = 0;
        int sizeNum = 20;
        if (!"".equals(page)) {
            pageNum = Integer.parseInt(page);
        }
        if (!"".equals(size)) {
            sizeNum = Integer.parseInt(size);
            if (sizeNum < 1)
                sizeNum = 1;
        }
        JsonBody jsonBody = new JsonBody();
        Pageable pageable = new PageRequest(pageNum, sizeNum);
        try {
            Page<UnitContentCPContent> pageData = unitContentService.adoptDeclareSearch(model,
                    pageable);
            jsonBody.setData(pageData);
            PageUtil pageUtil = new PageUtil();
            pageUtil.setNumber(pageData.getNumber());
            pageUtil.setSize(pageData.getSize());
            pageUtil.setTotalElements(pageData.getTotalElements());
            pageUtil.setTotalPages(pageData.getTotalPages());
            jsonBody.setPage(pageUtil);
            Map<String, Object> mapLink = new HashMap<String, Object>();
            // 首页
            Map<String, String> first = new HashMap<String, String>();
            first.put("href", request.getRequestURL() + "?sort=id,desc&size=" + pageData.getSize()
                    + "&page=0");
            mapLink.put("first", first);
            // 尾页
            Map<String, String> last = new HashMap<String, String>();
            last.put("href", request.getRequestURL() + "?sort=id,desc&size=" + pageData.getSize()
                    + "&page=" + (pageData.getTotalPages() - 1));
            mapLink.put("last", last);
            jsonBody.set_links(mapLink);

        } catch (Exception e) {
            logger.error(e.toString(), e);
            jsonBody.setErrorResult(e.getMessage());
            return jsonBody;
        }
        return jsonBody;
    }

    // 确认独家数据
    @CompareLog(clazz = CPContent.class, operateType = Oplog.OP_ADOPT, objName = Oplog.OBJ_TYPE_CPCONTENT, desc = "确认CP为独家数据")
    @RequestMapping(value = "/affirmExclusive", method = RequestMethod.GET)
    public JsonResponse affirmExclusive(HttpServletRequest request, Long id) {
        JsonResponse jsonResponse = new JsonResponse();
        try {
            HttpSession session = request.getSession();
            Operator oper = (Operator) session.getAttribute("user");
            CPContent cp = cpContentServer.findOne(id);
            UnitContent unitContent = new UnitContent();
            if (cp != null) {
                if (cp.getUnitContentId() == null) {
                    unitContent.setName(cp.getName());
                    unitContent.setContentNum(1);
                    unitContent.setUnitTime(new Date());
                    unitContent.setAdoptTime(new Date());
                    unitContent.setAdoptCpContentId(cp.getId());
                    unitContent.setAdoptOrgId(cp.getOrgId());
                    unitContent.setAdoptOperId(oper.getLoginName());
                    cp.setIsAdopted(1); // 采纳独家数据
                    UnitContent unit = unitContentRepository.save(unitContent);
                    cp.setUnitContentId(unit.getId());
                    cpContentRepository.save(cp);
                }
            }
            request.setAttribute(Oplog.OBJ_TYPE_CPCONTENT, cp);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            jsonResponse.setMessage("确认独家失败");
            return jsonResponse;
        }
        return jsonResponse;
    }

    // 取消独家数据
    @ActionLog(operateType = Oplog.OP_CANCELEXCLUSIVE, objName = Oplog.OBJ_TYPE_CPCONTENT, desc = "取消独家数据{name}")
    @RequestMapping(value = "/cancelExclusive", method = RequestMethod.GET)
    public JsonResponse cancelExclusive(HttpServletRequest request, Long id) {
        JsonResponse jsonResponse = new JsonResponse();
        try {
            CPContent cp = cpContentServer.findOne(id);
            if (cp != null) {
                if (cp.getUnitContentId() != null) {
                    UnitContent unit = unitContentRepository.findOne(cp.getUnitContentId());
                    unit.setAdoptCpContentId(null);
                    unitContentRepository.delete(unit.getId());
                }
                cp.setIsAdopted(2); // 取消独家数据的采纳
                cp.setUnitContentId(null);
                cp.setExclusive(false);
                cpContentRepository.save(cp);
            }
            request.setAttribute(Oplog.OBJ_TYPE_CPCONTENT, cp);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            jsonResponse.setMessage("取消独家失败");
            return jsonResponse;
        }
        return jsonResponse;
    }

    // 归并CP
    @ActionLog(operateType = Oplog.OP_MERGER, objName = Oplog.OBJ_TYPE_UNITCONTENT, desc = "归并CP数据{name}")
    @RequestMapping(value = "/mergerCP", method = RequestMethod.POST)
    public JsonResponse mergerCP(HttpServletRequest request, @Param("cpId") Long cpId,
            @Param("uId") Long uId, @Param("mergerName") String mergerName) {
        JsonResponse jsonResponse = new JsonResponse();
        try {
            // 获取CP元素
            CPContent cp = cpContentServer.findOne(cpId);
            if (cp != null) {
                UnitContent unit = new UnitContent();
                if (uId != null) {
                    UnitContent unitIsExist = unitContentRepository.findOne(uId);
                    if (unitIsExist != null) {
                        unitIsExist.setContentNum(unitIsExist.getContentNum() != null
                                ? unitIsExist.getContentNum() + 1 : 1);
                        unit = unitContentRepository.save(unitIsExist);
                    }
                } else {
                    List<UnitContent> list = unitContentRepository.findByName(mergerName);
                    if(!list.isEmpty()){
                        throw new Exception("归并内容已被采纳.");
                    }
                    UnitContent unitContent = new UnitContent();
                    unitContent.setContentNum(1);
                    unitContent.setName(mergerName);
                    unitContent.setUnitTime(new Date());
                    unit = unitContentRepository.save(unitContent);
                    jsonResponse.setData(unit.getId());
                }
                cp.setUnitContentId(unit.getId());
                // cp.setIsAdopted(CPContent.ISADOPTED_AWAIT);
                cpContentRepository.save(cp);
                request.setAttribute(Oplog.OBJ_TYPE_UNITCONTENT, unit);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            jsonResponse.setErrorResult(e.getMessage());
            return jsonResponse;
        }
        return jsonResponse;
    }

    // CP脱离
    @ActionLog(operateType = Oplog.OP_AWAY, objName = Oplog.OBJ_TYPE_UNITCONTENT, desc = "{name}CP数据脱离")
    @RequestMapping(value = "/unitAway", method = RequestMethod.GET)
    public JsonResponse unitAway(HttpServletRequest request, @Param("id") Long id) {
        JsonResponse jsonResponse = new JsonResponse();
        try {
            // 获取CP元素
            CPContent cp = cpContentServer.findOne(id);
            if (cp != null) {
                UnitContent unit = unitContentRepository.findOne(cp.getUnitContentId());
                cp.setUnitContentId(null);
                // cp.setIsAdopted(0);
                unit.setContentNum(unit.getContentNum() - 1);
                if (unit.getContentNum() < 1) {
                    unitContentRepository.delete(unit);
                } else {
                    unitContentRepository.save(unit);
                }
                cpContentRepository.save(cp);
                request.setAttribute(Oplog.OBJ_TYPE_UNITCONTENT, unit);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            jsonResponse.setMessage("CP数据脱离失败");
            return jsonResponse;
        }
        return jsonResponse;
    }

    // 内容采纳
    @CompareLog(clazz = CPContent.class, operateType = Oplog.OP_ADOPT, objName = Oplog.OBJ_TYPE_CPCONTENT, desc = "CP内容采纳")
    @RequestMapping(value = "/adoptCp", method = RequestMethod.GET)
    public JsonResponse adoptCp(HttpServletRequest request, @Param("id") Long id) {
        JsonResponse jsonResponse = new JsonResponse();
        try {
            HttpSession session = request.getSession();
            Operator oper = (Operator) session.getAttribute("user");
            // 获取CP
            CPContent cp = cpContentRepository.findOne(id);
            if (cp != null) {
                List<CPContent> cpList = cpContentRepository.searchCPContent(cp.getUnitContentId());
                for (int i = 0; i < cpList.size(); i++) {
                    cpList.get(i).setIsAdopted(CPContent.ISADOPTED_NOT);
                }
                cpContentRepository.save(cpList);
                UnitContent unitContent = unitContentRepository.findOne(cp.getUnitContentId());
                cp.setIsAdopted(CPContent.ISADOPTED_IS);
                unitContent.setAdoptCpContentId(cp.getId()); // 所采纳的CP的ID
                unitContent.setAdoptOrgId(cp.getOrgId()); // 所采纳的CP组织ID
                unitContent.setAdoptTime(new Date());
                unitContent.setAdoptOperId(oper.getLoginName());
                unitContentRepository.save(unitContent);
                cpContentRepository.save(cp);
            }
            request.setAttribute(Oplog.OBJ_TYPE_CPCONTENT, cp);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            jsonResponse.setMessage("内容采纳失败");
            return jsonResponse;
        }
        return jsonResponse;
    }

    // 取消采纳
    @ActionLog(operateType = Oplog.OP_CANCELAOPT, objName = Oplog.OBJ_TYPE_UNITCONTENT, desc = "取消采纳{name}")
    @RequestMapping(value = "/cancelAdopt", method = RequestMethod.GET)
    public JsonResponse cancelAdopt(HttpServletRequest request, @Param("id") Long id) {
        JsonResponse jsonResponse = new JsonResponse();
        try {
            // 获取CP
            CPContent cp = cpContentRepository.findOne(id);
            if (cp != null) {
                List<CPContent> cpList = cpContentRepository.searchCPContent(cp.getUnitContentId());
                for (int i = 0; i < cpList.size(); i++) {
                    cpList.get(i).setIsAdopted(CPContent.ISADOPTED_AWAIT);
                }
                cpContentRepository.save(cpList);
                UnitContent unitContent = unitContentRepository.findOne(cp.getUnitContentId());
                unitContent.setAdoptCpContentId(null);
                unitContent.setAdoptOrgId(null);
                unitContentRepository.save(unitContent);
                request.setAttribute(Oplog.OBJ_TYPE_UNITCONTENT, unitContent);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            jsonResponse.setMessage("取消采纳失败");
            return jsonResponse;
        }
        return jsonResponse;
    }

    // 导出Excel表格
    @ActionLog(operateType = Oplog.OP_EXPORT, objName = Oplog.OBJ_TYPE_UNITCONTENT, desc = "导出Excel表格")
    @RequestMapping(value = "/exportExcel", method = RequestMethod.POST)
    public JsonResponse exportExcel(HttpServletRequest request,
            @RequestAttribute MergerModel model) {
        JsonResponse jsonResponse = new JsonResponse();
        WriteDeclareExcelService declareExcelService = new WriteDeclareExcelService();
        List<EnumData> OrgEnumTypeResult = enumService.getEnumList("OrgEnum");
        Map<String, String> contentTypeResult = enumService.getEnumMap("contentType");
        Map<String, String> isAdoptedTypeResult = enumService.getEnumMap("isAdoptedType");
        Map<String, String> exclusiveTypeResult = enumService.getEnumMap("exclusive");

        List<UnitContentCPContent> pageData = unitContentRepository.exportExcel(model, null);
        HttpSession session = request.getSession();
        String path = (String) session.getAttribute("path");
        String fileOption = path + "excel/unitcontent/";
        File file = new File(fileOption);
        String fileName;
        try {
            if (!file.exists() && !file.isDirectory()) {
                file.mkdirs();
            }
            fileName = CodeUtils.createDateSerialNo() + ".xls";
            fileOption = fileOption + fileName;
        } catch (Exception e) {
            logger.error(e.toString(), e);
            jsonResponse.setErrorResult("创建excel文件失败");
            return jsonResponse;
        }
        declareExcelService.exportExcel(fileOption, pageData, OrgEnumTypeResult, contentTypeResult,
                isAdoptedTypeResult, exclusiveTypeResult);
        jsonResponse.setData("/excel/unitcontent/" + fileName);
        request.setAttribute(Oplog.OBJ_TYPE_UNITCONTENT, pageData.get(0).getUnitContent());
        return jsonResponse;
    }

}
